<script>
// works in Firefox only because of destructuring assignments
var SIZE=15
var BSIZE=5
var DIRS=[[1,0],[0,1],[1,1],[1,-1]]
var fdata = new Array()

function inField(x,y){
	return x>=0 && y>=0 && x<SIZE && y<SIZE
}
function inFieldBlock(block){
	alert('infield? '+block)
	var [x,y,dx,dy] = block
	return inField(x,y) && inField(x+(BSIZE-1)*dx, y+(BSIZE-1)*dy)
}
function blockIdxXY(block,idx){
	var [x,y,dx,dy] = block
	return [x+dx*idx, y+dy*idx]
}
function blockMarks(block){
	var [x,y,dx,dy] = block
	var s=''
	for( var i=0; i<BSIZE; i++ ){
		s += fdata[x+dx*i, y+dy*i]
	}
	return s	
}
function countInStr(str, mark){
	return str.length - str.replace(mark,'').length
}
function countInBlock(block, mark){
	return countInStr(blockMarks(block))
}
function revMark(m){
	if( m=='x' ) return 'o'
	if( m=='o' ) return 'x'
	alert('revMark arg wrong '+m)
}
function blocksAroundFilter(x,y,filter){
	var res = []
	alert(DIRS)
	for( var dxdy in DIRS ){
		var [dx,dy] = dxdy
		alert('dirs '+dx+' '+dy)
		for( var sh = 0; sh<5; sh++ ){
			var block = [x-dx*sh, y-dy*sh, dx, dy]
			if( inFieldBlock(block) && filter(block) ){
				res.push(block)
			}
		}
	}
	return res
}
function computerPlayer(lastMove,myMark,nextCallback){
	if( lastMove!=[] ){
		alert("last move "+lastMove)
		var [mx,my] = lastMove
		var opMark = revMark(myMark)
		var danger = blocksAroundFilter(mx,my,function(block){
			alert(blockMarks(block))
			return countInBlock(block,opMark)>=4
		})
		if( danger.length>0 ){
			var [x,y]=(danger[0], blockMarks(danger[0]).indexOf(' '))
			nextCallback(x,y)
			return
		}
	}

	for( var x=0; x<SIZE; x++ ){
		for( var y=0; y<SIZE; y++ ){
			if( fdata[x][y]==' ' ){
				nextCallback(x,y)
				return
			}
		}
	}
}

//====================== G U I =================================================



function countString(x,y,dx,dy,mark){
	c=1
	while( inField(x+c*dx, y+c*dy) && fdata[x+c*dx][y+c*dy]==mark ){
		c++
	}
	//alert(dx+" "+dy+" "+mark+" "+(c-1))
	return c-1
}
function isWinning(x,y){
	m = fdata[x][y]
	
	return countString(x,y,-1,0,m)+countString(x,y,1,0,m)>=4 ||
		countString(x,y,0,-1,m)+countString(x,y,0,1,m)>=4 ||
		countString(x,y,-1,-1,m)+countString(x,y,1,1,m)>=4 ||
		countString(x,y,-1,1,m)+countString(x,y,1,-1,m)>=4
}

var fieldClickCallback=function(){ alert('Game not started yet or not a human move!') }
function fieldClick(x,y){
	if( fdata[x][y]!=' ' ){
		alert("Cell not empty! "+x+" "+y)
	}else{
		if( fieldClickCallback!=0 ){
			fieldClickCallback(x,y)
		}
	}
}

function fieldMouseOver(x,y){
	//alert(x+" "+y)
	document.getElementById('fieldCell'+x+"_"+y).style.backgroundColor="#e0e0e0"
}
function fieldMouseOut(x,y){
	document.getElementById('fieldCell'+x+"_"+y).style.backgroundColor="transparent"
}

function setMark(x,y,mark){
	document.getElementById('fieldCell'+x+"_"+y).innerHTML=mark
}
function drawField(){
	document.write("<table id=field cellspacing=0 border=1>")
	for( var i=0; i<SIZE; i++ ){
		fdata[i] = new Array()
		document.write("<tr>")
		for( var j=0; j<SIZE; j++ ){
			fdata[i][j]=' '
			document.write(
			"<td width=20 heigth=20 align=center valign=middle "+
			"id=fieldCell"+j+"_"+i
			+" onmouseover='fieldMouseOver("+j+","+i+")' "
			+" onmouseout='fieldMouseOut("+j+","+i+")' "
			+" onclick='fieldClick("+j+","+i+")' "+">&nbsp;</td>")
		}
		document.write("</tr>")
	}
	document.write("</table>")
}
function humanPlayer(lastMove,myMark,nextCallback){
	fieldClickCallback = function(x,y){
		fieldClickCallback=0
		nextCallback(x,y)
	}
}
function msg(s){
	document.getElementById('msg').innerHTML=s
}
function colorify(color,msg){
	return '<span style="color:'+color+'">'+msg+'</span>'
}
function playerSelect(domId,markChar,color){
	type = document.getElementById(domId).value
	p = {
		f: type=='computer' ? computerPlayer : humanPlayer,
		mark: markChar,
		msg: colorify(color, 'Player '+markChar+ " " + type + " now - move!")
	}
	return p
}
function startGame(){
	p1 = playerSelect('sp1','x','blue') // {f:humanPlayer, mark:'x', msg:colorify('blue','p1 (x) - move!')}
	p2 = playerSelect('sp2','o','green') // {f:humanPlayer, mark:'o', msg:'p2 (o) - move!'}
	document.getElementById('startButton').disabled=true
	doGame(p1,p2,[])
}

function doGame(player,opponent,lastMove){
	msg(player.msg+" lastMove "+lastMove)
	player.f(lastMove,player.mark,function(x,y){
		fdata[x][y]=player.mark
		setMark(x,y,player.mark)
		if( isWinning(x,y) ){
			msg(colorify('red',player.mark + " is the winner!!!"))
			alert(player.mark + " is the winner!!!")
		}else{
			setTimeout(function(){ doGame(opponent,player,[x,y]) }, 500)		
		}
	})
}

drawField()
</script>
<div id=msg style='color:green'>Choose players and start game</div>
<div id=config>
	<select id=sp1 ><option>computer</option><option selected>human</option></select>
	vs
	<select id=sp2 ><option>computer</option><option>human</option></select>

	<button id=startButton onclick='startGame()' >Start</button>
</div>
<button onclick='window.location="5xxoo.html?"' >Reset</button>
